<?php
namespace app\controller\api\cms;
use app\FrontendController;
use app\model\cms\ArticleModel;
use app\model\tool\ImageModel;

class Article extends FrontendController
{


    public function index()
    {

        $res = [
            'code'=>0
        ];

        $uniacid = $_GET['i'];

        $cat = $_GET['category']??'';

        $model = new ArticleModel();
        
        if( !empty($cat) ){
            
            $res['list'] = $model->join( 'sh_cms_category', 'sh_cms_category.id = sh_cms_article.category_id', 'left' )
            ->where( 'sh_cms_category.name', 'like', '%'.$cat.'%' )
            ->where( 'sh_cms_article.uniacid', $uniacid )
            ->order( 'sh_cms_article.public_time', 'desc' )
            ->field( 'sh_cms_article.*,sh_cms_category.name as category_name' )
            ->select();
        }else{
            
            $res['list'] = $model->where( 'sh_cms_article.uniacid', $uniacid )->order( 'sh_cms_article.public_time', 'desc' )->select();            
        }



        // foreach( $res['list'] as $key=>$value ){
        //     $res['list'][$key]->image = ImageModel::resize2()
        // }

        return json( $res );
    }
    /**
     * 该文章信息
     */
    public function single( $id )
    {

        
        $res = [
            'code'=>0
        ];
        if( !$id ){
            $res['code'] = 1;
            $res['message'] = '参数不合法';
        }
        $res['article'] = ArticleModel::where( 'id', $id )->find( );


        $res['article']->content = html_entity_decode( $res['article']->content );

        $res['article']->image = ImageModel::resize2( $res['article']->image, 350,350 );

        if( !empty( $res['article']->custom  )  ){
            $res['article']->custom = json_decode( $res['article']->custom, true );
        }else{
            $res['article']->custom = [];
        }

        return json( $res );

    }

    /**
     * 通过标题查找
     */
    public function single_by_title( $title )
    {
        
        $uniacid = $_GET['i'];
        $res = [
            'code'=>0
        ];
        if( !$title ){
            $res['code'] = 1;
            $res['message'] = '参数不合法';
            return json( $res );
        }
        $res['article'] = ArticleModel::where( [ 'title' => $title, 'uniacid' => $uniacid ] )->find( );

        $res['article']->content = html_entity_decode( $res['article']->content );

        $res['article']->image = ImageModel::resize2( $res['article']->image, 350,350 );

        if( !empty( $res['article']->custom  )  ){
            $res['article']->custom = json_decode( $res['article']->custom, true );
        }else{
            $res['article']->custom = [];
        }

        return json( $res );

    }

}